package com.dhkj.circle.utils;

import com.dhkj.circle.constant.SQLConst;
import com.dhkj.circle.constant.SystemConst;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static com.dhkj.circle.ui.AppContext.sLogger;

public class DBHelper {

    private Connection connection = null;

    public Connection getConection() {
        try {
            Class.forName(SystemConst.CLASS_FORNAME);
//            jdbc:jtds:sqlserver://192.168.0.181:1433;DatabaseName=szy_dc
            String url = "jdbc:jtds:sqlserver://" + SQLConst.getInstance().getSqlIpAddr() + ":" + SQLConst.getInstance().getSqlPort() + ";DatabaseName=" + SQLConst.getInstance().getSqlName();
//            connection = DriverManager.getConnection(Const.SQL_URL, Const.SQL_NAME, Const.SQL_PASS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public Connection getConnector3() {
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
//            jdbc:jtds:sqlserver://192.168.0.181:1433;DatabaseName=szy_dc
            String url = "jdbc:jtds:sqlserver://" + SQLConst.getInstance().getSqlIpAddr() + ":" + SQLConst.getInstance().getSqlPort() + ";DatabaseName=" + SQLConst.getInstance().getSqlDBName() + ";loginTimeout=20;socketTimeout=20";
            connection = DriverManager.getConnection(url, SQLConst.getInstance().getSqlName(), SQLConst.getInstance().getSqlPass());
        } catch (Exception e) {
            sLogger.d(e.getMessage());
        }
        return connection;
    }

    public Connection getConectior2() {
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            String url = "jdbc:jtds:sqlserver://" + SQLConst.getInstance().getSqlIpAddr() + ":" + SQLConst.getInstance().getSqlPort();
            sLogger.d(url + SQLConst.getInstance().getSqlName() + SQLConst.getInstance().getSqlPass() + "\n" + SystemConst.CLASS_FORNAME);
            connection = DriverManager.getConnection(url, SQLConst.getInstance().getSqlName(), SQLConst.getInstance().getSqlPass());
        } catch (Exception e) {
            e.printStackTrace();
//            sLogger.d(e.getMessage());
        }
        return connection;
    }

    private PreparedStatement prepare(String SQL, boolean autoGeneratedKeys) {
        PreparedStatement ps = null;
        try {
            if (autoGeneratedKeys) {
                ps = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
            } else {
                ps = connection.prepareStatement(SQL);
            }
        } catch (SQLException e) {
            System.out.println("创建 PreparedStatement 对象失败: " + e.getMessage());
        }
        return ps;
    }

    public ResultSet query(String SQL, Object... params) {
        if (SQL == null || SQL.trim().isEmpty() || (!SQL.trim().toLowerCase().startsWith("select") && !SQL.trim().toLowerCase().startsWith("show"))) {
            throw new RuntimeException("你的SQL语句为空或不是查询语句");

        }
        ResultSet resultSet = null;
        getConection();
        if (params.length > 0) {
            /* 说明 有参数 传入，就需要处理参数 */
            PreparedStatement ps = prepare(SQL, false);
            try {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
                resultSet = ps.executeQuery();
            } catch (SQLException e) {
                System.out.println("执行SQL失败: " + e.getMessage());
            } finally {
                close(ps, resultSet);
            }
        } else {
            /* 说明没有传入任何参数 */
            Statement st = statement();
            try {
                resultSet = st.executeQuery(SQL); // 直接执行不带参数的 SQL 语句
            } catch (SQLException e) {
                System.out.println("执行SQL失败: " + e.getMessage());
            } finally {
                try {
                    if (resultSet != null) {
                        resultSet.close();
                    }
                    if (st != null) {
                        st.close();
                    }
                    if (connection != null) {
                        connection.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resultSet;
    }

    /**
     * 创建 Statement 对象
     */
    private Statement statement() {
        Statement st = null;
        try {
            st = connection.createStatement();
        } catch (SQLException e) {
            System.out.println("创建 Statement 对象失败: " + e.getMessage());
        }
        return st;
    }

    private void close(PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
